package com.fjwt.gz.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson2.JSONObject;
import com.fjwt.gz.core.constants.CS;
import com.fjwt.gz.core.constants.Constants;
import com.fjwt.gz.core.exception.BizException;
import com.fjwt.gz.core.third.bo.VirtualGoodsSupplierBo;
import com.fjwt.gz.core.third.interfaces.OutSideSupplierService;
import com.fjwt.gz.core.utils.SpringBeansUtil;
import com.fjwt.gz.db.dto.FansOrderVirtualDTO;
import com.fjwt.gz.db.entity.AwardVirtualEntity;
import com.fjwt.gz.db.entity.AwardVirtualInsideEntity;
import com.fjwt.gz.db.entity.AwardVirtualOutsideEntity;
import com.fjwt.gz.db.entity.AwardVirtualSupplierEntity;
import com.fjwt.gz.db.entity.FansAwardEntity;
import com.fjwt.gz.db.entity.FansOrderVirtualEntity;
import com.fjwt.gz.db.entity.FansUserEntity;
import com.fjwt.gz.service.mapper.FansOrderVirtualMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fjwt.gz.zhyx.sms.SmsUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 用户订单流水表---虚拟奖品（直冲） 服务实现类
 * </p>
 *
 * @author shiyonghao
 * @since 2025-04-09
 */
@Slf4j
@Service
public class FansOrderVirtualService extends ServiceImpl<FansOrderVirtualMapper, FansOrderVirtualEntity> {
    @Autowired
    private FansOrderVirtualMapper fansOrderVirtualMapper;
    @Autowired
    private AwardVirtualService awardVirtualService;
    @Autowired
    private AwardVirtualInsideService awardVirtualInsideService;
    @Autowired
    private AwardVirtualOutsideService awardVirtualOutsideService;
    @Autowired
    private AwardVirtualSupplierService awardVirtualSupplierService;
    @Autowired
    private FansAwardService fansAwardService;
    @Autowired
    private FansUserService fansUserService;

    // 订单回调接口
    public static final String ORDER_NOTIFY_URL = "/api/outSide/Supplier/yangyuwangluo/order/notify";

    /**
     * 下单
     */
    @Transactional
    public void createOrder(FansOrderVirtualDTO fansOrderVirtualDTO) {
        if (ObjectUtils.isEmpty(fansOrderVirtualDTO.getFansAwardId())) {
            throw new BizException("请选择要充值的奖品");
        }
        if (ObjectUtils.isEmpty(fansOrderVirtualDTO.getAttach())) {
            throw new BizException("请输入要充值的手机号");
        }
        if (ObjectUtils.isEmpty(fansOrderVirtualDTO.getCode())) {
            throw new BizException("请输入验证码");
        }
        checkSmsCode(fansOrderVirtualDTO.getAttach(), fansOrderVirtualDTO.getCode(), 7);

        FansAwardEntity fansAwardEntity = fansAwardService.getById(fansOrderVirtualDTO.getFansAwardId());
        if (ObjectUtils.isEmpty(fansAwardEntity) || Constants.AWARD.VIRTUAL_COUPON != fansAwardEntity.getAwardType() || fansAwardEntity.getState() != 0) {
            throw new BizException("所选奖品异常");
        }
        if (!fansOrderVirtualDTO.getFansId().equals(fansAwardEntity.getFansId())) {
            throw new BizException("非本人奖品，无法充值");
        }
        AwardVirtualEntity awardVirtualEntity = awardVirtualService.getById(fansAwardEntity.getAwardId());
        if (ObjectUtils.isEmpty(awardVirtualEntity) || 2 != awardVirtualEntity.getState()) {
            throw new BizException("所选奖品异常");
        }

        FansUserEntity fansUserEntity = fansUserService.getOne(FansUserEntity.gw()
                .eq(FansUserEntity::getFansId, fansAwardEntity.getFansId()).eq(FansUserEntity::getAppId, fansOrderVirtualDTO.getAppid())
                .eq(FansUserEntity::getType, 1));

        AwardVirtualInsideEntity awardVirtualInsideEntity = awardVirtualInsideService.getById(awardVirtualEntity.getVirtualInsideId());
        if (ObjectUtils.isEmpty(awardVirtualInsideEntity)) {
            throw new BizException("所选权益异常");
        }

        AwardVirtualOutsideEntity awardVirtualOutsideEntity = awardVirtualOutsideService.getById(awardVirtualInsideEntity.getVirtualOutsideId());
        AwardVirtualSupplierEntity awardVirtualSupplierEntity = awardVirtualSupplierService.getById(awardVirtualOutsideEntity.getVirtualSupplierId());
        if (ObjectUtils.isEmpty(awardVirtualSupplierEntity) || 0 == awardVirtualSupplierEntity.getState() || ObjectUtils.isEmpty(awardVirtualSupplierEntity.getSupplierName())) {
            throw new BizException("供应商状态异常，请检查");
        }
        OutSideSupplierService outSideSupplierService = SpringBeansUtil.getBean(awardVirtualSupplierEntity.getSupplierName() + "OutSideSupplierService", OutSideSupplierService.class);
        if (outSideSupplierService == null) {
            throw new BizException("该供应商暂不支持该功能");
        }
        DateTime date = DateUtil.date();

        String orderNo = fansUserEntity.getOpenId() + date.getTime();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("goodsId", awardVirtualOutsideEntity.getThirdGoodsId());
        jsonObject.put("buyNum", 1);
        jsonObject.put("sysUserNo", orderNo);
        jsonObject.put("attach", fansOrderVirtualDTO.getAttach());
        jsonObject.put("notifyUrl", fansOrderVirtualDTO.getNotifyDomain() + ORDER_NOTIFY_URL);

        VirtualGoodsSupplierBo virtualGoodsSupplierBo = new VirtualGoodsSupplierBo();
        BeanUtils.copyProperties(awardVirtualSupplierEntity, virtualGoodsSupplierBo);
        JSONObject reqJson = outSideSupplierService.createOrder(jsonObject, virtualGoodsSupplierBo);

        // 三方（供应商）订单号
        String thirdOrderNo = reqJson.getString("orderno");
        FansOrderVirtualEntity fansOrderVirtualEntity = new FansOrderVirtualEntity();
        fansOrderVirtualEntity.setOrderVirtualNo(orderNo);
        fansOrderVirtualEntity.setThirdOrderNo(thirdOrderNo);
        fansOrderVirtualEntity.setFansAwardId(fansAwardEntity.getFansAwardId());
        fansOrderVirtualEntity.setThirdGoodsId(awardVirtualOutsideEntity.getThirdGoodsId());
        fansOrderVirtualEntity.setGoodsName(awardVirtualInsideEntity.getGoodsName());
        fansOrderVirtualEntity.setMoney(awardVirtualInsideEntity.getMarketPrice());
        fansOrderVirtualEntity.setCallbackUrl(jsonObject.getString("notifyUrl"));
        fansOrderVirtualEntity.setAttach(fansOrderVirtualDTO.getAttach());
        fansOrderVirtualEntity.setReceipt(fansOrderVirtualDTO.getReceipt());
        fansOrderVirtualEntity.setState(3);
        fansOrderVirtualMapper.insert(fansOrderVirtualEntity);

        fansAwardEntity.setState(6);
        fansAwardService.updateById(fansAwardEntity);
    }

    /**
     * 订单查询
     */
    public void queryOrder(FansOrderVirtualDTO fansOrderVirtualDTO) {

    }

    /**
     * 校验验证码
     * @param phone
     * @param smsCode
     * @param flag
     */
    private void checkSmsCode(String phone, String smsCode, Integer flag) {
        JSONObject smsCOde = SmsUtil.getSmsCOde(CS.SYS_ROLE_TYPE.MCH, phone, flag);
        String smsCodeRedis = smsCOde.getString("code");
        if (!smsCodeRedis.equals(smsCode)){
            throw new BizException("验证码错误");
        }
    }
}
